﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Windows.Forms;
using Message = System.Messaging.Message;

namespace MsgQueueTest
{
    public partial class MainForm : Form
    {
        private MessageQueue messageQueue;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MsgbackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            SetTitle("Running");
            while (true)
            {
                try
                {
                    Message message = messageQueue.Receive();
                    if (message == null) break;
                    SetLog(string.Format("{0}:{1}\r\n", message.Label, ((Email)message.Body).Query));
                }
                catch (MessageQueueException ex)
                {
                    SetLog(ex.ToString());
                }
            }
        }

        private void MsgbackGroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            SetTitle("Stopped");
            messageQueue.Close();
            messageQueue = null;
        }

        private delegate void SetTitleDelegate(string titile);

        public void SetTitle(string title)
        {
            if (InvokeRequired)
            {
                this.Invoke(new SetTitleDelegate(SetTitle), new object[] { title });

            }
            else
            {
                Text = title;
            }
        }

        public void SetLog(string title)
        {
            if (InvokeRequired)
            {
                this.Invoke(new SetTitleDelegate(SetLog), new object[] { title });

            }
            else
            {
                LogTextBox.Text = LogTextBox.Text + title;
            }
        }


        private void StartButton_Click(object sender, EventArgs e)
        {
            if (messageQueue == null)
            {
                messageQueue = new MessageQueue(QueueTextBox.Text.Trim());
                messageQueue.Formatter = new MyXmlMessageFormater(new Type[] { typeof(Email) }, Encoding.Unicode);

                MsgbackGroundWorker.RunWorkerAsync();
            }
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            if (messageQueue != null)
            {
                messageQueue.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Email email = new Email();
            //messageQueue.Send(email);
            MailManager.SendMail();
        }
    }
}
